package com.glowdayz.glowmee;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.glowdayz.common.ActivityManager;
import com.glowdayz.common.CDialog;
import com.glowdayz.common.ImageDownloader;
import com.glowdayz.common.XmlParser;
import com.glowdayz.model.ProductCMD;
import com.glowdayz.model.UserInfo;


public class ListCategoryProduct extends Activity implements OnScrollListener, OnItemClickListener {
	
	private ActivityManager am = ActivityManager.getInstance();
	
	ListView listCategoryProduct = null;
	
	ArrayList<ProductCMD> list = null;
	DataAdapter adapter = null;
	// Footer 레이아웃
	LinearLayout llFooter = null;
	LinearLayout llHeader = null;
	
	int paramId = 0;
	String paramFirst = null;
	String paramTitle = null;
	String url = null, productUrl = null;
	
	int paramIdProduct = 0;
	String paramProductTitle = null;
	
	/********** 페이지 구현 **********/
	private int page = 1;						// 현재 페이지
	private final static int pageSize = 20;		// 한 페이지에 보일 수
	private int totalCount = 0;
	
	LinearLayout editerTitleLaylout = null, editerProductLayout = null, productTitleLaylout = null;
	
	ArrayList<ProductCMD> editerList = null;
	int editerTotal = 0;
	int editerCount = 0;
	ImageView beforeBt = null, forwardBt = null;
	ImageView productImg = null;
	RatingBar productRatingBar = null;
	TextView productTitle = null, productBrand = null, productVolume = null, productPrice = null, productRating = null, 
			productRatingCount = null, promotionText = null;
	
	String[] brandArr = null;
	
	int paramFilter = 0, paramOrder = 0;
	String paramPrice1 = "", paramPrice2 = "", paramBrandTitle = "", paramKeyWord = "";
	
	TextView productCount = null;
	
	boolean newFilter = false;
	
	private ViewPager mPager;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_category_product);
		
		am.addActivity(this);
		
		Intent fromIntent = getIntent();
		paramId = fromIntent.getIntExtra("PARAM_id", 0);
		paramFirst = fromIntent.getStringExtra("PARAM_first");
		paramTitle = fromIntent.getStringExtra("PARAM_title");
		
		paramFilter = fromIntent.getIntExtra("PARAM_filter", 0);
		paramOrder = fromIntent.getIntExtra("PARAM_order", 0);
		paramPrice1 = fromIntent.getStringExtra("PARAM_price1");
		paramPrice2 = fromIntent.getStringExtra("PARAM_price2");
		paramBrandTitle = fromIntent.getStringExtra("PARAM_brand");
		paramKeyWord = fromIntent.getStringExtra("PARAM_keyWord");
		newFilter = fromIntent.getBooleanExtra("PARAM_newFilter", false);
		
		ImageView backBt = (ImageView) findViewById(R.id.backBt);
		backBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		backBt.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		ImageView okBt = (ImageView) findViewById(R.id.okBt);
		okBt.setImageResource(R.drawable.pick_search);
		okBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		okBt.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(ListCategoryProduct.this, ProductFilter.class);
				intent.putExtra("PARAM_id", paramId);
				intent.putExtra("PARAM_first", paramFirst);
				intent.putExtra("PARAM_title", paramTitle);
				
				intent.putExtra("PARAM_order", paramOrder);
				intent.putExtra("PARAM_brand", paramBrandTitle);
				intent.putExtra("PARAM_price1", paramPrice1);
				intent.putExtra("PARAM_price2", paramPrice2);
				intent.putExtra("PARAM_keyWord", paramKeyWord);
				
				if (newFilter) {
					intent.putExtra("PARAM_newFilter", newFilter);
					startActivityForResult(intent, 1);
				} else {
					intent.putExtra("PARAM_newFilter", newFilter);
					intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
					startActivity(intent);
				}
				
			}
		});
		
		TextView textTitle = (TextView) findViewById(R.id.textTitle);
		textTitle.setText(paramTitle);
		
		listCategoryProduct = (ListView) findViewById(R.id.listCategoryProduct);
		
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		llHeader = (LinearLayout) inflater.inflate(R.layout.list_editer_product_item, null);
		listCategoryProduct.addHeaderView(llHeader);
		
		editerTitleLaylout = (LinearLayout) llHeader.findViewById(R.id.editerTitleLaylout);
		
		productTitleLaylout = (LinearLayout) llHeader.findViewById(R.id.productTitleLaylout);
		productCount = (TextView) llHeader.findViewById(R.id.productCount);
		TextView recommendProductTitle = (TextView) llHeader.findViewById(R.id.recommendProductTitle);
		if (UserInfo.getInstance().getUSER_NICKNAME() != null) {
			recommendProductTitle.setText(UserInfo.getInstance().getUSER_NICKNAME() + "님을 위한 추천 제품");
		}
		
		 // 메인 디지안과 별도로 레이아웃을 불러오기
		LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		llFooter = (LinearLayout) li.inflate(R.layout.list_footer, null);
		llFooter.setVisibility(View.GONE);
		listCategoryProduct.addFooterView(llFooter);
		
		listCategoryProduct.setOnScrollListener(this);
        
        list = new ArrayList<ProductCMD>();
		adapter = new DataAdapter(this, list);
		listCategoryProduct.setAdapter(adapter);
		listCategoryProduct.setOnItemClickListener(this);
		
		editerList = new ArrayList<ProductCMD>();
		
		url = getResources().getString(R.string.server_url) + "/glowmee/hotEditerProductXml.do?type=EDITER&idSecondCategory=" + paramId;
		
		(new HotProductWorker()).execute();
		
		if (paramFilter == 0) {
			productUrl = getResources().getString(R.string.server_url) + "/glowmee/listProductXml.do?" +
					"page=" + page + "&count=" + pageSize + "&type=category&id=" + paramId;
		} else if (paramFilter == 1) {
			productUrl = getResources().getString(R.string.server_url) + "/glowmee/listProductXml.do?" +
					"page=" + page + "&count=" + pageSize + "&type=category&id=" + paramId +
					"&order=" + paramOrder + "&price1=" + paramPrice1 + "&price2=" + paramPrice2 + "&brandTitle=" + paramBrandTitle +
					"&keyWord=" + paramKeyWord;
		}
		
		(new ProductListWorker()).execute();
		
	}
	
	private class PagerAdapterClass extends PagerAdapter{
		
		private LayoutInflater mInflater;

		public PagerAdapterClass(Context c){
			super();
			mInflater = LayoutInflater.from(c);
		}
		
		@Override
		public int getCount() {
			return editerList.size();
		}

		@Override
		public Object instantiateItem(View pager, int position) {
			View v = mInflater.inflate(R.layout.list_editer_product, null);
			
			ProductCMD item = editerList.get(position);
			
			beforeBt = (ImageView) v.findViewById(R.id.beforeBt);
			beforeBt.setOnTouchListener(new OnTouchListener() {
	            @Override
	            public boolean onTouch(View v, MotionEvent event) {
	                switch (event.getAction()) {
	                    case MotionEvent.ACTION_DOWN: {
	                        ImageView view = (ImageView) v;
	                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
	                        view.invalidate();
	                        break;
	                    }
	                    case MotionEvent.ACTION_UP:
	                    case MotionEvent.ACTION_CANCEL: {
	                        ImageView view = (ImageView) v;
	                        view.getDrawable().clearColorFilter();
	                        view.invalidate();
	                        break;
	                    }
	                }
	                return false;
	            }
	        });
			
			forwardBt = (ImageView) v.findViewById(R.id.forwardBt);
			forwardBt.setOnTouchListener(new OnTouchListener() {
	            @Override
	            public boolean onTouch(View v, MotionEvent event) {
	                switch (event.getAction()) {
	                    case MotionEvent.ACTION_DOWN: {
	                        ImageView view = (ImageView) v;
	                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
	                        view.invalidate();
	                        break;
	                    }
	                    case MotionEvent.ACTION_UP:
	                    case MotionEvent.ACTION_CANCEL: {
	                        ImageView view = (ImageView) v;
	                        view.getDrawable().clearColorFilter();
	                        view.invalidate();
	                        break;
	                    }
	                }
	                return false;
	            }
	        });
			
			beforeBt.setVisibility(View.GONE);
			forwardBt.setVisibility(View.GONE);
			
			if (editerList.size() > 1) {
				forwardBt.setVisibility(View.VISIBLE);
				final int afterPosition = position + 1;
				forwardBt.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						mPager.setCurrentItem(afterPosition);
					}
				});
				
				if (position > 0) {
					beforeBt.setVisibility(View.VISIBLE);
					final int beforePosition = position - 1;
					beforeBt.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							mPager.setCurrentItem(beforePosition);
						}
					});
					
					if (editerList.size() - 1 == position) {
						forwardBt.setVisibility(View.GONE);
					}
				}
			}
			
			final int finalIdProduct = item.getIdProduct();
			final String finalProductTitle = item.getProductTitle();
			editerProductLayout = (LinearLayout) v.findViewById(R.id.editerProductLayout);
			editerProductLayout.setOnTouchListener(new OnTouchListener() {
				@Override
				public boolean onTouch(View v, MotionEvent arg1) {
					v.setBackgroundResource(android.R.drawable.list_selector_background);
					return false;
				}
			});
			editerProductLayout.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(ListCategoryProduct.this, ViewProduct.class);
					intent.putExtra("PARAM_id", finalIdProduct);
					intent.putExtra("PARAM_title", finalProductTitle);
					startActivity(intent);
				}
			});
			
			productImg = (ImageView) v.findViewById(R.id.productImg);
			productRatingBar = (RatingBar) v.findViewById(R.id.productRatingBar);
			productRatingBar.setOnTouchListener(new OnTouchListener() {
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					return true;
				}
			});
			productTitle = (TextView) v.findViewById(R.id.productTitle);
			productBrand = (TextView) v.findViewById(R.id.productBrand);
			productVolume = (TextView) v.findViewById(R.id.productVolume);
			productPrice = (TextView) v.findViewById(R.id.productPrice);
			productRating = (TextView) v.findViewById(R.id.productRating);
			productRatingCount = (TextView) v.findViewById(R.id.productRatingCount);
			promotionText = (TextView) v.findViewById(R.id.promotionText);
			
			editerTitleLaylout.setVisibility(View.VISIBLE);
			editerProductLayout.setVisibility(View.VISIBLE);
			
			productTitle.setText(item.getProductTitle());
			productBrand.setText(item.getIdBrandValue());
			productVolume.setText(item.getVolume());
			productPrice.setText(item.getPrice() + "원");
			productRating.setText(String.valueOf(item.getRatingAvg()));
			if (item.getRationCount() > 0) {
				productRatingCount.setText(" (" + item.getRationCount() + ")");
			} else {
				productRatingCount.setVisibility(View.GONE);
			}
			promotionText.setText(item.getPromotionText());
			
			ImageDownloader.getInstance().download(getResources().getString(R.string.server_url) + item.getImage().trim(), productImg);
			productRatingBar.setStepSize((float) 0.1);
			productRatingBar.setRating(Float.parseFloat(String.valueOf(item.getRatingAvg())));
			
    		((ViewPager)pager).addView(v, 0);
    		
    		return v; 
		}

		@Override
		public void destroyItem(View pager, int position, Object view) {	
			((ViewPager)pager).removeView((View)view);
		}
		
		@Override
		public boolean isViewFromObject(View pager, Object obj) {
			return pager == obj; 
		}

		@Override public void restoreState(Parcelable arg0, ClassLoader arg1) {}
		@Override public Parcelable saveState() { return null; }
		@Override public void startUpdate(View arg0) {}
		@Override public void finishUpdate(View arg0) {}
	}
	
	public class HotProductWorker extends AsyncTask<Object, ProductCMD, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(ListCategoryProduct.this);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				int idProduct = 0;
				String productTitle = null;
				String idBrandValue = null;
				String volume = null;
				int price = 0;
				double ratingAvg = 0.0;
				int rationCount = 0;
				String promotionText = null;
				String thumbnail = null;
				
				
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("totalArticleCount")) {
							parser.next();
							editerTotal = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("idProduct")) {
							parser.next();
							idProduct = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("productTitle")) {
							parser.next();
							productTitle = parser.getText();
						} else if (tag.equals("idBrandValue")) {
							parser.next();
							idBrandValue = parser.getText();
						} else if (tag.equals("volume")) {
							parser.next();
							volume = parser.getText();
						} else if (tag.equals("price")) {
							parser.next();
							price = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("ratingAvg")) {
							parser.next();
							ratingAvg = Double.parseDouble(parser.getText().trim());
						} else if (tag.equals("rationCount")) {
							parser.next();
							rationCount = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("promotionText")) {
							parser.next();
							promotionText = parser.getText();
						} else if (tag.equals("thumbnail")) {
							parser.next();
							thumbnail = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("item")) {
							ProductCMD item = new ProductCMD(idProduct, idBrandValue, productTitle, volume, price, promotionText, 
									ratingAvg, rationCount, thumbnail);
							editerList.add(item);
							//publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(ProductCMD... param) {
		}

		@Override
		protected void onPostExecute(Object param) {
			mPager = (ViewPager) llHeader.findViewById(R.id.pager);
			
			if (editerTotal > 0) {
				mPager.setAdapter(new PagerAdapterClass(getApplicationContext()));
			} else {
				mPager.setVisibility(View.GONE);
			}
			
			CDialog.hideLoading();
		}
		
		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(ListCategoryProduct.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new HotProductWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
	public class DataAdapter extends ArrayAdapter<ProductCMD> {
		private LayoutInflater inflater = null;

		// 생성자. 파라미터에 전달되는 List의 제너릭스 선언에 주의한다.
		public DataAdapter(Context context, List<ProductCMD> objects) {
			super(context, 0, objects);
			inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		// ArrayList에 할당된 각 항목을 하나씩 추출하여 list_item.xml에 표현시키는 메서드
		// 이 메서드는 ListView에 의해서 호출된다.
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			/** 모든 컴포넌트의 최상위 클래스 */
			View view = null;

			// 데이터를 저장할 View 선언. view 객체는 "list_item.xml"파일을 의미한다.
			if (convertView == null) {
				view = inflater.inflate(R.layout.list_product_item, null);
			} else {
				view = convertView;
			}

			// 하나의 데이터 항목을 추출한다.
			ProductCMD item = getItem(position);

			// 추출한 데이터가 존재한다면 "list_item.xml"안의 컨트롤들을 추출하여 처리한다.
			if (item != null) {
				view.setOnTouchListener(new OnTouchListener() {
					@Override
					public boolean onTouch(View v, MotionEvent arg1) {
						v.setBackgroundResource(android.R.drawable.list_selector_background);
						return false;
					}
				});
				
				ImageView productImg = (ImageView) view.findViewById(R.id.productImg);
				ImageView brandImg = (ImageView) view.findViewById(R.id.brandImg);
				
				TextView productTitle = (TextView) view.findViewById(R.id.productTitle);
				TextView productVolume = (TextView) view.findViewById(R.id.productVolume);
				TextView productPrice = (TextView) view.findViewById(R.id.productPrice);
				TextView productRating = (TextView) view.findViewById(R.id.productRating);
				TextView productRatingCount = (TextView) view.findViewById(R.id.productRatingCount);
				if (item.getRationCount() > 0) {
					productRatingCount.setVisibility(View.VISIBLE);
					productRatingCount.setText(" (" + item.getRationCount() + ")");
				} else {
					productRatingCount.setVisibility(View.GONE);
				}
				
				RatingBar productRatingBar = (RatingBar) view.findViewById(R.id.productRatingBar);
				productRatingBar.setFocusable(false);
				productRatingBar.setOnTouchListener(new OnTouchListener() {
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						return true;
					}
				});
				productRatingBar.setStepSize((float) 0.1);
				productRatingBar.setRating(Float.parseFloat(String.valueOf(item.getRatingAvg())));
				
				productTitle.setText(item.getProductTitle());
				
				if (item.getVolume().length() > 10) {
					productVolume.setText(item.getVolume().substring(0, 9) + "...");
				} else {
					productVolume.setText(item.getVolume());
				}
				
				
				productPrice.setText(item.getPrice() + "원");
				productRating.setText(String.valueOf(item.getRatingAvg()));
				
				if (item.getCreate_date().equals("null")) {
					productImg.setImageResource(R.drawable.empty_product);
				} else {
					ImageDownloader.getInstance().download(getResources().getString(R.string.server_url) + item.getCreate_date().trim(), productImg);
				}
				
				
				if (item.getImage().equals("null")) {
					brandImg.setImageResource(R.drawable.empty_logo);
				} else {
					ImageDownloader.getInstance().download(getResources().getString(R.string.server_url) + item.getImage().trim(), brandImg);
				}
			}
			return view;
		}
	}
	
	public class ProductListWorker extends AsyncTask<Object, ProductCMD, Object> {
		@Override
		protected void onPreExecute() {
			llFooter.setVisibility(View.VISIBLE);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			
			XmlPullParser parser = XmlParser.getInstance().getParser(productUrl);
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				int idProduct = 0;
				String productTitle = null;
				int idBrand = 0;
				String idBrandValue = null;
				String volume = null;
				int price = 0;
				double ratingAvg = 0.0;
				int rationCount = 0;
				String image = null;
				String productImg = null;
				
				
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("totalArticleCount")) {
							parser.next();
							totalCount = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("idProduct")) {
							parser.next();
							idProduct = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("productTitle")) {
							parser.next();
							productTitle = parser.getText();
						} else if (tag.equals("idBrand")) {
							parser.next();
							idBrand = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("idBrandValue")) {
							parser.next();
							idBrandValue = parser.getText();
						} else if (tag.equals("volume")) {
							parser.next();
							volume = parser.getText();
						} else if (tag.equals("price")) {
							parser.next();
							price = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("ratingAvg")) {
							parser.next();
							ratingAvg = Double.parseDouble(parser.getText().trim());
						} else if (tag.equals("rationCount")) {
							parser.next();
							rationCount = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("brandThumbnail")) {
							parser.next();
							image = parser.getText();
						} else if (tag.equals("productThumbnail")) {
							parser.next();
							productImg = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("item")) {
							ProductCMD item = new ProductCMD(
									idProduct, idBrand, idBrandValue, productTitle, volume, price, ratingAvg, rationCount, image, productImg);
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(ProductCMD... param) {
			adapter.add(param[0]);
		}

		@Override
		protected void onPostExecute(Object param) {
			llFooter.setVisibility(View.GONE);
			productCount.setText("(" + totalCount + ")");
			if (paramFilter == 1 && totalCount == 0) {
				AlertDialog.Builder temp = new AlertDialog.Builder(new ContextThemeWrapper(ListCategoryProduct.this, android.R.style.Theme_Holo_Light_Dialog));
				temp.setMessage("해당하는 제품이 없습니다.");
				temp.setCancelable(false);
				temp.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(ListCategoryProduct.this, ProductFilter.class);
						intent.putExtra("PARAM_id", paramId);
						intent.putExtra("PARAM_first", paramFirst);
						intent.putExtra("PARAM_title", paramTitle);
						
						intent.putExtra("PARAM_order", paramOrder);
						intent.putExtra("PARAM_brand", paramBrandTitle);
						intent.putExtra("PARAM_price1", paramPrice1);
						intent.putExtra("PARAM_price2", paramPrice2);
						intent.putExtra("PARAM_keyWord", paramKeyWord);
						
						startActivityForResult(intent, 1);
						finish();
					}
				});
				temp.create();
				temp.show();
			}
		}
		
		@Override
		protected void onCancelled() {
			llFooter.setVisibility(View.GONE);
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(ListCategoryProduct.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new ProductListWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}

	// 화면에 리스트의 마지막 아이템이 보여지는 체크
	boolean lastItemVisibleFlag = false;
	
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		lastItemVisibleFlag = (totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount);
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && lastItemVisibleFlag) {
			int pageCount = ((totalCount -1) / pageSize) + 1;
			if (pageCount > 0 && page < pageCount) {
				page++;
				if (paramFilter == 0) {
					productUrl = getResources().getString(R.string.server_url) + "/glowmee/listProductXml.do?" +
							"page=" + page + "&count=" + pageSize + "&type=category&id=" + paramId;
				} else if (paramFilter == 1) {
					productUrl = getResources().getString(R.string.server_url) + "/glowmee/listProductXml.do?" +
							"page=" + page + "&count=" + pageSize + "&type=category&id=" + paramId +
							"&order=" + paramOrder + "&price1=" + paramPrice1 + "&price2=" + paramPrice2 + "&brandTitle=" + paramBrandTitle +
							"&keyWord=" + paramKeyWord;
				}
				(new ProductListWorker()).execute();
			}
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		ProductCMD select = adapter.getItem(arg2 - 1);
		int id = select.getIdProduct();
		String title = select.getProductTitle();
		Intent intent = new Intent(this, ViewProduct.class);
		intent.putExtra("PARAM_id", id);
		intent.putExtra("PARAM_title", title);
		startActivity(intent);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			
			newFilter = true;
			
			paramFilter = data.getIntExtra("PARAM_filter", 0);
			paramOrder = data.getIntExtra("PARAM_order", 0);
			paramPrice1 = data.getStringExtra("PARAM_price1");
			paramPrice2 = data.getStringExtra("PARAM_price2");
			paramBrandTitle = data.getStringExtra("PARAM_brand");
			paramKeyWord = data.getStringExtra("PARAM_keyWord");
			
			adapter.clear();
			
			if (paramFilter == 0) {
				productUrl = getResources().getString(R.string.server_url) + "/glowmee/listProductXml.do?" +
						"page=" + page + "&count=" + pageSize + "&type=category&id=" + paramId;
			} else if (paramFilter == 1) {
				productUrl = getResources().getString(R.string.server_url) + "/glowmee/listProductXml.do?" +
						"page=" + page + "&count=" + pageSize + "&type=category&id=" + paramId +
						"&order=" + paramOrder + "&price1=" + paramPrice1 + "&price2=" + paramPrice2 + "&brandTitle=" + paramBrandTitle +
						"&keyWord=" + paramKeyWord;
				
			}
			
			(new ProductListWorker()).execute();
		}
	}
	
    @Override
	protected void onDestroy() {
		super.onDestroy();
		am.removeActivity(this);
	}
}
